package com.sgb.kjwl.view.ui.activity.self.publish;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySelfLeaseListBinding;
import com.sgb.kjwl.di.machine.DaggerMachineComponent;
import com.sgb.kjwl.di.machine.MachineModule;
import com.sgb.kjwl.model.entity.LeasePublishEntity;
import com.sgb.kjwl.model.entity.self.LeaseStateEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.kjwl.view.ui.activity.house.LeaseHousesActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.LeaseStateAdapter;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.LeasePublishDialog;
import com.sgb.kjwl.viewmodel.self.publish.SelfLeaseListModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 租赁发布列表
 */
public class SelfLeaseListActivity extends AppActivity {
    private ActivitySelfLeaseListBinding binding;

    @Inject
    SelfLeaseListModel viewModel;
    private LeaseStateAdapter adapter;
    private List<DictEntity3> classDatas;
    private List<DictEntity3> statusDatas;
    private DictWindow5 classPopWindow;
    private DictWindow5 typePopWindow;
    private String statusNo = "";//状态no
    private String classNo = "";//分类no

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMachineComponent.builder().appComponent(appComponent)
                .machineModule(new MachineModule(this))
                .build()
                .inject(this);
    }


    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, SelfLeaseListActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(SelfLeaseListActivity.this, R.layout.activity_self_lease_list);
        initXRecyclerView();
        initPopWindow();
        binding.topLayout.ivBack.setOnClickListener(v -> finish());
        binding.topLayout.tvRight.setOnClickListener(v -> showBottomDialog());
        binding.classLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);
        binding.topLayout.editSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.topLayout.editSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    closeKeybord();
                    viewModel.map.get().put("title", binding.topLayout.editSearch.getText().toString());
//                    adapter.setStatus(statusNo);
                    viewModel.getPublishListModel(false);
                }
                return false;
            }
        });

    }

    @Override
    protected void init() {
        initClassData();
        initStatusData();
        getData(false);
    }


    private void initXRecyclerView() {
        if (adapter == null) {
            adapter = new LeaseStateAdapter(getActivity(), null);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.rlvView.setLayoutManager(layoutManager);
        binding.rlvView.addItemDecoration(new RecyclerCustomDecoration(0,
                0,
                0,
                getResources().getDimension(R.dimen.dp10), getResources().getColor(R.color.color_F5F5F5)));
        binding.rlvView.setAdapter(adapter);
        binding.rlvView.setLoadingMoreEnabled(true);
        binding.rlvView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getPublishListModel(false);
            }

            @Override
            public void onLoadMore() {
                viewModel.getPublishListModel(true);
            }
        });
        adapter.setItemCallBack(new LeaseStateAdapter.ItemCallBack() {
            @Override
            public void del(String id, String type) {
                optDelState(type, id);
            }

            @Override
            public void up(String id, String type) {
                optUpState(type, id);
            }

            @Override
            public void down(String id, String type) {
                optDownState(type, id);
            }

            @Override
            public void detail(String id, String type) {
                viewModel.getH5Url(type, id);
            }
        });
    }

    private void initPopWindow() {
        classPopWindow = new DictWindow5(getActivity());
        classPopWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                classNo = dictEntity.getId();
                binding.tvClass.setText(dictEntity.getName());
                getData(false);
            }
        });
        classPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.classArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });

        typePopWindow = new DictWindow5(getActivity());
        typePopWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                statusNo = dictEntity.getId();
                binding.tvType.setText(dictEntity.getName());
                getData(false);
            }
        });
        typePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                binding.typeArrowView.setImageResource(R.mipmap.ic_down_arrow_n);
            }
        });
    }

    private void getData(boolean isLoadMore) {
        viewModel.map.get().put("type", classNo);
        viewModel.map.get().put("status", statusNo);
        viewModel.getPublishListModel(isLoadMore);
    }

    public void showList(List<LeaseStateEntity> datas, boolean isLoadMore) {
        if (isLoadMore) {
            binding.rlvView.loadMoreComplete();
            if (datas.size() != 0) {
                adapter.addDatas(datas);
            }
        } else {
            if (datas == null || datas.size() == 0) {
                datas = new ArrayList<>();
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }
            binding.rlvView.refreshComplete();
            binding.rlvView.setLoadingMoreEnabled(true);
            adapter.setDatas(datas);
        }
    }

    private void optUpState(String type, String id) {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("上架提示")
                .setMsg("您确定要上架当前信息？")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        switch (type) {
                            case "1":
                                viewModel.upDownMachineStateModel("1", id);
                                break;
                            case "2":
                                viewModel.upDownDeviceStateModel("1", id);
                                break;
                            case "3":
                                viewModel.upDownCarStateModel("1", id);
                                break;
                            case "4":
                                viewModel.upDownHouseStateModel("1", id);
                                break;
                            case "5":
                                viewModel.upDownLandModel("1", id);
                                break;
                            case "6":
                                viewModel.upDownFactoryStateModel("1", id);
                                break;
                            case "7":
                                viewModel.upDownFarmModel("1", id);
                                break;
                        }

                    }

                    @Override
                    public void onLeftClick() {

                    }
                }).show();

    }

    private void optDownState(String type, String id) {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("下架提示")
                .setMsg("您确定要下架当前信息？")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        switch (type) {
                            case "1":
                                viewModel.upDownMachineStateModel("2", id);
                                break;
                            case "2":
                                viewModel.upDownDeviceStateModel("2", id);
                                break;
                            case "3":
                                viewModel.upDownCarStateModel("2", id);
                                break;
                            case "4":
                                viewModel.upDownHouseStateModel("2", id);
                                break;
                            case "5":
                                viewModel.upDownLandModel("2", id);
                                break;
                            case "6":
                                viewModel.upDownFactoryStateModel("2", id);
                                break;
                            case "7":
                                viewModel.upDownFarmModel("2", id);
                                break;
                        }
                    }

                    @Override
                    public void onLeftClick() {

                    }
                }).show();
    }

    private void optDelState(String type, String id) {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("删除提示")
                .setMsg("您确定要删除当前信息？ 删除后，将不可恢复")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        switch (type) {
                            case "1":
                                viewModel.delMachineModel(id);
                                break;
                            case "2":
                                viewModel.delDeviceModel(id);
                                break;
                            case "3":
                                viewModel.delCarModel(id);
                                break;
                            case "4":
                                viewModel.delHouseModel(id);
                                break;
                            case "5":
                                viewModel.delLandModel(id);
                                break;
                            case "6":
                                viewModel.delFactoryModel(id);
                                break;
                            case "7":
                                viewModel.delFarmModel(id);
                                break;
                        }

                    }

                    @Override
                    public void onLeftClick() {

                    }
                }).show();

    }

//    public void showOptSuccess() {
//        viewModel.getPublishListModel(false);
//    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(LeaseEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_LEASE_PUBLISH_FILTER) {
            viewModel.getPublishListModel(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.class_layout:
                if (null != classDatas && classDatas.size() > 0) {
                    showClassPop();
                }
                break;
            case R.id.type_layout:
                if (null != statusDatas && statusDatas.size() > 0) {
                    showStatusPop();
                }
                break;
        }
    }

    private List<LeasePublishEntity> getList() {
        List<LeasePublishEntity> list = new ArrayList<>();
        list.add(new LeasePublishEntity("机械出租", "械"));
        list.add(new LeasePublishEntity("设备出租", "设"));
        list.add(new LeasePublishEntity("车辆出租", "车"));
        list.add(new LeasePublishEntity("房产出租", "房"));
        list.add(new LeasePublishEntity("土地出租", "地"));
        list.add(new LeasePublishEntity("工厂出租", "厂"));
        list.add(new LeasePublishEntity("农机出租", "农"));
        return list;
    }

    private void showBottomDialog() {
        LeasePublishDialog leasePublishDialog = new LeasePublishDialog(getActivity(), null);
        leasePublishDialog.setData(getList());
        leasePublishDialog.setDialogClickCallBack(s -> {
            switch (s) {
                case "械"://机械
                    LeaseMachineActivity.start(SelfLeaseListActivity.this);
                    break;
                case "设": //设备
                    DevicePublishActivity.start(SelfLeaseListActivity.this);
                    break;
                case "车"://车辆
                    CarPublishActivity1.start(SelfLeaseListActivity.this);
                    break;
                case "房"://房产
                    LeaseHousesActivity.start(SelfLeaseListActivity.this);
                    break;
                case "地"://土地
                    LeaseLandActivity.start(SelfLeaseListActivity.this);
                    break;
                case "厂"://工厂
                    LeaseFactoryActivity.start(SelfLeaseListActivity.this);
                    break;
                case "农"://农机
                    LeaseFarmActivity.start(SelfLeaseListActivity.this);
                    break;
            }
        }).show();
    }


    private void initClassData() {
        //状态:1 机械 2 设备3 车辆4 房产 5 土地 6工厂 7 农机 空字符 全部
        classDatas = new ArrayList<>();
        classDatas.add(new DictEntity3("", "不限"));
        classDatas.add(new DictEntity3("1", "机械租赁"));
        classDatas.add(new DictEntity3("2", "设备租赁"));
        classDatas.add(new DictEntity3("3", "车辆租赁"));
        classDatas.add(new DictEntity3("4", "房产租赁"));
        classDatas.add(new DictEntity3("5", "土地租赁"));
        classDatas.add(new DictEntity3("6", "工厂租赁"));
        classDatas.add(new DictEntity3("7", "农机租赁"));
        classPopWindow.setData(classDatas);
        classPopWindow.setCheckDefaultById("");
    }

    private void initStatusData() {
        //状态:0草稿，1 上架 2 下架 3 已拒绝，4 审核中
        statusDatas = new ArrayList<>();
        statusDatas.add(new DictEntity3("", "不限"));
        statusDatas.add(new DictEntity3("1", "已上架"));
        statusDatas.add(new DictEntity3("2", "已下架"));
        //如果是企业用户 则 增加3 审核不过，4 审核中
        String myCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        if (!TextUtils.isEmpty(myCompanyNo) && !"0".equals(myCompanyNo)) {
            statusDatas.add(new DictEntity3("4", "审核中"));
            statusDatas.add(new DictEntity3("3", "已拒绝"));
        }
        statusDatas.add(new DictEntity3("0", "草稿"));
        typePopWindow.setData(statusDatas);
        typePopWindow.setCheckDefaultById("");
    }

    private void showClassPop() {
        binding.classArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
        classPopWindow.setCheckDefaultById(classNo);
        classPopWindow.showPopwindow(binding.roomLayout, 0, 2);
    }

    private void showStatusPop() {
        binding.typeArrowView.setImageResource(R.mipmap.ic_up_arrow_n);
        typePopWindow.setCheckDefaultById(statusNo);
        typePopWindow.showPopwindow(binding.roomLayout, 0, 2);
    }

}

